package cn.smile.excel.writer.xssf;

import cn.smile.excel.writer.WriteExcel;
import cn.smile.exception.write.WriteDataNullException;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 支持.xlsx的写入
 *
 * @Author: 毛苏宇
 * User: me
 * Date: 2019/12/1
 * Time: 18:16
 * Description: 支持.xlsx的写入
 */
public class XSSFWriteExcel implements WriteExcel {

    /**
     * XSSF基本属性
     */
    private XSSF xssf;

    public XSSFWriteExcel(String path, String name) {
        this.xssf=new XSSF(path + File.separator + name);
    }

    public void addTitle(String[] title) throws WriteDataNullException {
        addData(title);
    }

    public void addData(String[] data) throws WriteDataNullException {
        int size = data.length;
        if (null == data || 0 == size) {
            throw new WriteDataNullException();
        }
        //实时获取行数
        int rowNum = this.xssf.getSheet().getPhysicalNumberOfRows();
        XSSFRow xssfRow = this.xssf.getSheet().createRow(rowNum);
        for (int i = 0; i < size; i++) {
            xssfRow.createCell(i, CellType.STRING).setCellValue(data[i]);
        }
    }

    public void addData(ArrayList<String[]> titleAndData) throws WriteDataNullException {
        for (String[] titleAndDatum : titleAndData) {
            addData(titleAndDatum);
        }
    }

    public void write() {
        if (null != this.xssf.getWorkbook()) {
            try {
                this.xssf.getWorkbook().write(new FileOutputStream(this.xssf.getPath()));
                this.xssf.getWorkbook().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
